package com.xingkeduo.business.order.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.xingkeduo.dto.CraftsmanDTO;
import com.xingkeduo.dto.param.VerifyReedRedeemCodeParam;
import com.xingkeduo.dto.transter.appointment.AppointmentSubmit;
import com.xingkeduo.dto.transter.appointment.CheckNewUserCouponDto;
import com.xingkeduo.dto.transter.shop.*;
import com.xingkeduo.dto.transter.thirdparty.*;
import com.xingkeduo.dto.wxma.WxMaUserInfo;
import com.xingkeduo.remote.feign.AdminFeignService;
import com.xingkeduo.remote.feign.MarketingFeignService;
import com.xingkeduo.remote.feign.StoreFeignService;
import com.xingkeduo.remote.feign.ThirdPartyChannelService;
import com.xingkeduo.utils.ResponseUtils;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description TODO
 * @Date 2019/5/16 10:57
 * @Created 情绪十分不稳定的Shadow
 */
@Slf4j
@Service
public class CheckService {

    @Resource
    private StoreFeignService storeFeignService;

    @Resource
    private ThirdPartyChannelService thirdPartyChannelService;

    @Resource
    private MarketingFeignService marketingFeignService;

    @Resource
    private AdminFeignService adminFeignService;

    public AppointmentSubmit selfAddOrder(CheckNewUserCouponDto checkNewUserCouponDto){
        long shopId = Long.parseLong(checkNewUserCouponDto.getStore_id());
        ShopListIdAndName shopListIdAndName = new ShopListIdAndName();
        //查询当前店铺信息
        ResponseUtils<ShopsDTO> shopsDTOResponseUtils = storeFeignService.doGet(shopId);
        if(shopsDTOResponseUtils.success()){
            ShopsDTO shopsDTO= shopsDTOResponseUtils.getData();
            shopListIdAndName.setStore_id(checkNewUserCouponDto.getStore_id());
            shopListIdAndName.setStore_name(shopsDTO.getName());
        }
        Integer[] array2 = {1,2,3,4};
        ResponseUtils<List<ShopsIdAndNameDto>> shopsList = storeFeignService.getShopsList(array2);
        AppointmentSubmit appointmentSubmit = new AppointmentSubmit();
        shopListIdAndName.setStore_list(shopsList.getData());
        appointmentSubmit.setError(0);
        appointmentSubmit.setReason(0);
        appointmentSubmit.setContent(shopListIdAndName);
        return appointmentSubmit;
    }

    public AppointmentSubmit channel(CheckNewUserCouponDto checkNewUserCouponDto){
        log.info("进入channel方法，核销码--->>>"+checkNewUserCouponDto.getCode());
        AppointmentSubmit appointmentSubmit = new AppointmentSubmit();
        log.info("getAdmin:{}", checkNewUserCouponDto.getF_user_id());
        JSONObject object = new JSONObject();
        object.put("id", checkNewUserCouponDto.getF_user_id());
        ResponseUtils<WxMaUserInfo> consumerInfo = adminFeignService.getConsumerInfo(object.toString());
        log.info("getAdmin response:{}", consumerInfo);
        if(!consumerInfo.success()){
            appointmentSubmit.setError(Integer.parseInt(consumerInfo.getCode()));
            appointmentSubmit.setReason(consumerInfo.getMsg());
            appointmentSubmit.setContent(new ArrayList<>());
            return appointmentSubmit;
        }

        String shopId = checkNewUserCouponDto.getStore_id();
        String code = checkNewUserCouponDto.getCode().replace(" ", "");
        int length = code.length();
        //星客多核销
        if (length == 8){
            log.info("自主核验参数--->>>自主核销码code："+code+",用户Id："+Long.parseLong(checkNewUserCouponDto.getF_user_id()));
            String result = marketingFeignService.bindBagReceiveAccount(code, Long.parseLong(checkNewUserCouponDto.getF_user_id()));
            log.info(result);
            checkLocalParsing(result, appointmentSubmit, code, shopId);
        }
        //美团点评核销
        else if (length == 10){
            ResponseUtils<ShopsDTO> shopsDTOResponseUtils = storeFeignService.doGet(Long.parseLong(shopId));
            if(shopsDTOResponseUtils.success()){
                ShopsDTO shopsDTO = shopsDTOResponseUtils.getData();
                log.info("三方核验参数--->>>美团核销码code："+code);
                String result = thirdPartyChannelService.dianpingCoupons(shopId, code);
                System.out.println(result);
                log.info(result);
                checkThirdpartyParsing(result, appointmentSubmit, code, shopId, shopId, checkNewUserCouponDto.getF_user_id(), "6", shopsDTO.getName());
            }
        }
        //口碑核销
        else if (length == 12){
            //TODO 查询店铺绑定对应 口碑店铺ID 需要查询
            //1.查询当前店铺对应的口碑店铺Id
            ResponseUtils<ShopsDTO> shopsDTOResponseUtils = storeFeignService.doGet(Long.parseLong(shopId));
            if(shopsDTOResponseUtils.success()){
                ShopsDTO shopsDTO = shopsDTOResponseUtils.getData();
                if(StringUtils.isBlank(shopsDTO.getKouBeiShopsNum())){
                    appointmentSubmit.setError(7);
                    appointmentSubmit.setReason("对应口碑门店不存在");
                    appointmentSubmit.setContent(new ArrayList<>());
                    return appointmentSubmit;
                }
                //2.核验对应核销码是否配置 or 还有剩余库存 TODO 还未实现 2019-06-20 以实现
                //2-1.获取核销码对应商品Id
                String resultCheck = thirdPartyChannelService.koubeiCouponsCheck(shopsDTO.getKouBeiShopsNum(), code);
                log.info("check口碑结果--->>>"+resultCheck);
                JSONObject jsonObject = JSONObject.parseObject(resultCheck);
                String resultStatus = jsonObject.get("status").toString();
                //TODO 假马甲逻辑开始 之后会去掉 只有一种情况会进入这里 核销结果为{"status":0,"code":"UN_EFFECTIVE","msg":"未核销，兑换码不能用于此门店"}
                if("0".equals(resultStatus)){
                    String resultCode = jsonObject.get("code").toString();
                    String resultItemId = jsonObject.get("item_id").toString();
                    //判断口碑check结果 if 是 {"status":0,"code":"UN_EFFECTIVE","msg":"未核销，兑换码不能用于此门店"}
                    if("UN_EFFECTIVE".equals(resultCode)){
                        //用itemId, Long.parseLong(checkNewUserCouponDto.getF_user_id()) 去获取 实际核销店铺 and 三方核销店铺
                        log.info("根据口碑商品id 查询是否可以兑换queryActivityCouponBagByItemId开始");
                        log.info("resultItemId参数："+resultItemId);
                        log.info("Long.parseLong(checkNewUserCouponDto.getF_user_id())参数："+Long.parseLong(checkNewUserCouponDto.getF_user_id()));
                        String resultMarketCheck = marketingFeignService.queryActivityCouponBagByItemId(resultItemId, Long.parseLong(checkNewUserCouponDto.getF_user_id()));
                        System.out.println(resultMarketCheck);
                        log.info("查询是否可以兑换queryActivityCouponBagByItemId结果resultMarketCheck--->>>"+resultMarketCheck);
                        //获取到两组店铺数据
                        JSONObject jsonQueryCoupon = JSONObject.parseObject(resultMarketCheck);
                        String jsonQueryCouponStatus = jsonQueryCoupon.get("status").toString();
                        if("1".equals(jsonQueryCouponStatus)){
                            String jsonQueryCouponDate = jsonQueryCoupon.get("data").toString();
                            JSONObject jsonExchangeInfo = JSONObject.parseObject(jsonQueryCouponDate);
                            String storeIds = jsonExchangeInfo.get("storeIds").toString();
                            String thirdStoreIds = jsonExchangeInfo.get("thirdStoreIds").toString();
                            log.info("实际核销门店"+ storeIds);
                            log.info("三方核销门店"+ thirdStoreIds);
                            List<String> storeList = Arrays.asList(storeIds.split(","));
                            List<String> thirdStoreList = Arrays.asList(thirdStoreIds.split(","));
                            //判断传入店铺shopId 是否在实际核销店铺内
                            log.info("传入店铺ID:"+shopId+"---是否在实际核销店铺"+storeIds+"内---storeList.contains(shopId)>>>"+storeList.contains(shopId));
                            if(storeList.contains(shopId)){
                                ResponseUtils<ShopsDTO> shopsDTOUtils = storeFeignService.doGet(Long.parseLong(thirdStoreList.get(0)));
                                if(shopsDTOUtils.success()) {
                                    ShopsDTO shops = shopsDTOUtils.getData();
                                    //2.核验对应核销码是否配置 or 还有剩余库存 TODO 还未实现 2019-06-20 以实现
                                    //2-1.获取核销码对应商品Id
                                    String resultThirdCheck = thirdPartyChannelService.koubeiCouponsCheck(shops.getKouBeiShopsNum(), code);
                                    log.info("check口碑结果--->>>" + resultThirdCheck);
                                    JSONObject jsonThirdObject = JSONObject.parseObject(resultThirdCheck);
                                    String resultThirdStatus = jsonThirdObject.get("status").toString();
                                    if("1".equals(resultThirdStatus)){
                                        //3.三方核验 TODO 需要提前校验下 口碑店铺ID是否存在 shopsDTO.getKouBeiShopsNum()
                                        log.info("三方核验参数--->>>口碑店铺ID："+shopsDTO.getKouBeiShopsNum()+",口碑核销码code："+code);
                                        String result = thirdPartyChannelService.koubeiCoupons(shops.getKouBeiShopsNum(), code);
                                        System.out.println(result);
                                        log.info(result);
                                        return checkThirdpartyParsing(result, appointmentSubmit, code, shopId, String.valueOf(shops.getId()),checkNewUserCouponDto.getF_user_id(), "15", shopsDTO.getName());
                                    }
                                }else{
                                    appointmentSubmit.setError(3);
                                    appointmentSubmit.setReason("门店不存在");
                                    appointmentSubmit.setContent(new ArrayList<>());
                                    return appointmentSubmit;
                                }
                            }else {
                                appointmentSubmit.setError(6);
                                appointmentSubmit.setReason("未核销，兑换码不能用于此门店");
                                appointmentSubmit.setContent(new ArrayList<>());
                                return appointmentSubmit;
                            }
                        }else{
                            appointmentSubmit.setError(5);
                            appointmentSubmit.setReason(jsonQueryCoupon.get("msg").toString());
                            appointmentSubmit.setContent(new ArrayList<>());
                            return appointmentSubmit;
                        }
                    }
                }
                //TODO 假马甲逻辑结束

                //拿着套餐ID去查询实际核销门店
                if("1".equals(resultStatus)){
                    //2-2.获取对应商品情况
                    String resultData = jsonObject.get("data").toString();
                    JSONObject jsonData = JSONObject.parseObject(resultData);
                    String itemId = jsonData.get("item_id").toString();
                    String resultMarketCheck = marketingFeignService.queryActivityCouponBagByItemId(itemId, Long.parseLong(checkNewUserCouponDto.getF_user_id()));
                    log.info(resultMarketCheck);
                    JSONObject jsonQueryCoupon = JSONObject.parseObject(resultMarketCheck);
                    String jsonQueryCouponStatus = jsonQueryCoupon.get("status").toString();
                    if("1".equals(jsonQueryCouponStatus)){
                        //3.三方核验 TODO 需要提前校验下 口碑店铺ID是否存在 shopsDTO.getKouBeiShopsNum()
                        log.info("三方核验参数--->>>口碑店铺ID："+shopsDTO.getKouBeiShopsNum()+",口碑核销码code："+code);
                        String result = thirdPartyChannelService.koubeiCoupons(shopsDTO.getKouBeiShopsNum(), code);
                        System.out.println(result);
                        log.info(result);
                        return checkThirdpartyParsing(result, appointmentSubmit, code, shopId, shopId, checkNewUserCouponDto.getF_user_id(), "15", shopsDTO.getName());
                    }else{
                        appointmentSubmit.setError(5);
                        appointmentSubmit.setReason(jsonQueryCoupon.get("msg").toString());
                        appointmentSubmit.setContent(new ArrayList<>());
                    }
                }else{
                    appointmentSubmit.setError(4);
                    appointmentSubmit.setReason("三方核销前，未查询到对应活动Id");
                    appointmentSubmit.setContent(new ArrayList<>());
                }
            }else{
                appointmentSubmit.setError(3);
                appointmentSubmit.setReason("门店不存在");
                appointmentSubmit.setContent(new ArrayList<>());
            }
        }else{
            appointmentSubmit.setError(2);
            appointmentSubmit.setReason("兑换码不正确");
            appointmentSubmit.setContent(new ArrayList<>());
        }
        return appointmentSubmit;
    }

    public AppointmentSubmit getCouponBagInfo(CheckNewUserCouponDto checkNewUserCouponDto){
        AppointmentSubmit appointmentSubmit = new AppointmentSubmit();
        String result = marketingFeignService.queryMarketingBagByRedeemCode(checkNewUserCouponDto.getCode());
        JSONObject jsonObject = JSONObject.parseObject(result);
        String resultStatus = jsonObject.get("status").toString();
        String resultCode = jsonObject.get("code").toString();
        if("1".equals(resultStatus)) {
            String data = jsonObject.get("data").toString();
            TService tService = JSONObject.parseObject(data, TService.class);
            CouponBagInfo couponBagInfo = conver(tService);
            appointmentSubmit.setError(0);
            appointmentSubmit.setReason(0);
            appointmentSubmit.setContent(couponBagInfo);
            return appointmentSubmit;
        }
        String resultMsg = jsonObject.get("msg").toString();
        appointmentSubmit.setError(Integer.parseInt(resultCode));
        appointmentSubmit.setReason(resultMsg);
        appointmentSubmit.setContent(new ArrayList<>());
        return appointmentSubmit;
    }

    //第三方核销数据 处理
    private AppointmentSubmit checkThirdpartyParsing(String result, AppointmentSubmit appointmentSubmit, String code, String shopId, String thirdShopId, String userId, String type, String shopName){
        log.info("三方核销数据处理入参：" );
        log.info("三方接口核销结果--result：" + result);
        log.info("核销码--code：" + code);
        log.info("传入店铺Id--shopId：" + shopId);
        log.info("三方可核销门店ID--thirdShopId：" + thirdShopId);
        log.info("用户ID--userId：" + userId);
        log.info("三发类型--type：" + type);
        log.info("店铺名称--shopName：" + shopName);
        JSONObject jsonObject = JSONObject.parseObject(result);
        String resultStatus = jsonObject.get("status").toString();
        //resultStatus = 1 核销成功  resultStatus = 0 核销失败
        if("1".equals(resultStatus)){
            String data = jsonObject.get("data").toString();
            System.out.println(data);
            JSONObject jsonCouponId = JSONObject.parseObject(data);
            String itemId = jsonCouponId.getString("item_id");
            //1.插入核销表数据 TODO 2019-05-18 还未插入核销表  2019-05-20 对接完成
            //1-1.组装数据 请求营销系统 TODO 2019-05-18 还未组装数据 2019-05-20 对接完成
            VerifyReedRedeemCodeParam verifyReedRedeemCodeParam = new VerifyReedRedeemCodeParam();
            verifyReedRedeemCodeParam.setF_koubei_order_no(jsonCouponId.getString("koubei_order_no"));
            verifyReedRedeemCodeParam.setF_store_id(shopId);
            verifyReedRedeemCodeParam.setF_code(code);
            verifyReedRedeemCodeParam.setF_type(type);
            verifyReedRedeemCodeParam.setF_channel("2");
            verifyReedRedeemCodeParam.setF_user_id(userId);
            verifyReedRedeemCodeParam.setF_koubei_item_id(itemId);
            verifyReedRedeemCodeParam.setF_remark(shopName);
            verifyReedRedeemCodeParam.setF_third_store_id(thirdShopId);
            //团购商品市场价
            verifyReedRedeemCodeParam.setF_market_price(jsonCouponId.getString("original_price"));
            //团购商品售价
            verifyReedRedeemCodeParam.setF_selling_price(jsonCouponId.getString("current_price"));
            String resultCodeId = marketingFeignService.verifyUserPurchaseRedeemCode(verifyReedRedeemCodeParam);
            log.info("生成核销数据返回--->>>"+resultCodeId);
            JSONObject jsonObjectCodeId = JSONObject.parseObject(resultCodeId);
            String statusCodeId = jsonObjectCodeId.get("status").toString();
            if("0".equals(statusCodeId)){
                appointmentSubmit.setError(Integer.parseInt(jsonObjectCodeId.get("code").toString()));
                appointmentSubmit.setReason(jsonObjectCodeId.get("msg"));
                appointmentSubmit.setContent(new ArrayList<>());
                return appointmentSubmit;
            }
            //2.获取到返回的商品ID 去营销系统兑换优惠劵
            String dataCodeId = jsonObjectCodeId.get("data").toString();
            JSONObject jsonObjectDate = JSONObject.parseObject(dataCodeId);
            log.info("请求营销系统,入参fId--->>>"+jsonObjectDate.get("fId").toString());
            log.info("请求营销系统,入参fCouponBagId--->>>"+jsonObjectDate.get("fCouponBagId").toString());
            String resultCheck = marketingFeignService.bindUserPurchaseRedeemCode(jsonObjectDate.get("fId").toString(), jsonObjectDate.get("fCouponBagId").toString());
            log.info("三方兑换优惠包结果--->>>"+resultCheck);
            //3.根据兑换信息拼装获取优惠包结果 得到Available_quantity参数组装返回给小程序
            return checkLocalParsing(resultCheck, appointmentSubmit, code, shopId);
        }
        String resultCode = jsonObject.get("code").toString();
        String resultMsg = jsonObject.get("msg").toString();
        if("6".equals(type)){
            appointmentSubmit.setError(Integer.parseInt(resultCode));
        }else if("15".equals(type)){
            appointmentSubmit.setError(1);
        }
        appointmentSubmit.setReason(resultMsg);
        appointmentSubmit.setContent(new ArrayList<>());
        return appointmentSubmit;
    }
    //自主核销数据 处理
    private AppointmentSubmit checkLocalParsing(String result, AppointmentSubmit appointmentSubmit, String code, String shopId){
        int vouchersCount = 0;
        int cardCount = 0;
        JSONObject jsonObject = JSONObject.parseObject(result);
        String resultStatus = jsonObject.get("status").toString();
        String resultCode = jsonObject.get("code").toString();
        if("1".equals(resultStatus)){
            String data = jsonObject.get("data").toString();
            System.out.println(data);
            JSONArray tableData = JSONArray.parseArray(data);
            List<DiscountPackageDto> discountPackageDtos = JSONObject.parseArray(tableData.toJSONString(), DiscountPackageDto.class);
            for(DiscountPackageDto discountPackageDto : discountPackageDtos){
                if(discountPackageDto.getMarketingType() == 0){
                    vouchersCount += discountPackageDto.getTotalQuantity();
                }else if(discountPackageDto.getMarketingType() == 1){
                    cardCount += discountPackageDto.getTotalQuantity();
                }
            }
            //TODO 当前数据是写死的 2019-05-16 需要对接真是数据 2019-05-17 已经对接动态数据
            CheckLocalResultDto checkLocalResultDto = new CheckLocalResultDto();
            checkLocalResultDto.setCode(code);
            checkLocalResultDto.setStore_id(shopId);
            checkLocalResultDto.setVouchers_available_quantity(String.valueOf(vouchersCount));
            checkLocalResultDto.setCard_available_quantity(String.valueOf(cardCount));
            //TODO 需要替换的数据
            appointmentSubmit.setError(0);
            appointmentSubmit.setReason(0);
            appointmentSubmit.setContent(checkLocalResultDto);
            return appointmentSubmit;
        }
        String resultMsg = jsonObject.get("msg").toString();
        appointmentSubmit.setError(1);
        appointmentSubmit.setReason(resultMsg);
        appointmentSubmit.setContent(resultCode);
        return appointmentSubmit;
    }

    private CouponBagInfo conver(TService tService){
        CouponBagInfo couponBagInfo = new CouponBagInfo();
        List<CouponBag> couponBags = new ArrayList<>();
        List<CouponBag> cardBags = new ArrayList<>();
        CodeInfo codeInfo = new CodeInfo();
        codeInfo.setStatus(0);
        codeInfo.setType(3);
        codeInfo.setSub_type(tService.getfSubType());
        codeInfo.setItem_id("zsyh001");
        codeInfo.setAvailable_quantity(0);
        codeInfo.setKoubei_order_no(tService.getfKoubeiOrderNo());
        codeInfo.setPay_price("18.90");
        codeInfo.setActivity_code_id(0);
        List<MarketingResponseVo> coupon_bag = tService.getCoupon_bag();
        for(MarketingResponseVo marketingResponseVo: coupon_bag){
            CouponBag couponBag = new CouponBag();
            couponBag.setName(marketingResponseVo.getName());
            String storeIds = marketingResponseVo.getStoreIds();
    		if(StringUtils.isNotBlank(storeIds)) {
    			if(storeIds.startsWith("0,")) {
    				storeIds = storeIds.substring(2, storeIds.length());
    			}
    			if(storeIds.endsWith(",0")) {
    				storeIds = storeIds.substring(0, storeIds.length()-2);
    			}
    		}
            couponBag.setStore_id(storeIds);
            couponBag.setQuantity(marketingResponseVo.getTotalQuantity());
            couponBag.setCoupon_id("1550");
            couponBag.setType("1");
            couponBag.setCoupon_detail_id("4468978");
            couponBag.setUse_end_time(useEndTime(marketingResponseVo.getUseType(), marketingResponseVo.getUsePeriod(), marketingResponseVo.getUseStartTime(), marketingResponseVo.getUseEndTime()));
            couponBag.setCard_type(marketingResponseVo.getServiceType());
            BigDecimal leastAmount = marketingResponseVo.getLeastCost()==null?BigDecimal.valueOf(0):marketingResponseVo.getLeastCost();
			leastAmount = leastAmount.subtract(leastAmount.setScale(1,BigDecimal.ROUND_DOWN)).compareTo(BigDecimal.valueOf(0)) > 0 ? leastAmount : leastAmount.setScale(1, BigDecimal.ROUND_DOWN);
			couponBag.setLeast_cost(leastAmount.toString());
    		String couponAmount = marketingResponseVo.getCouponAmount()==null ? "" : marketingResponseVo.getCouponAmount().toString();
    		if(StringUtils.isBlank(couponAmount)) {
    			couponBag.setReduce_cost(Lists.newArrayList("0","0"));
    		}else {
    			BigDecimal amount = new BigDecimal(couponAmount);
    			if("DISCOUNT".equalsIgnoreCase(couponBag.getCard_type())) {
    				amount= amount.multiply(BigDecimal.valueOf(10)).setScale(1, BigDecimal.ROUND_DOWN);
					BigDecimal one = amount.setScale(0,BigDecimal.ROUND_DOWN);
					BigDecimal two =amount.subtract(one).multiply(BigDecimal.valueOf(10)).setScale(0,BigDecimal.ROUND_DOWN);
    				couponBag.setDiscount(Lists.newArrayList(one+"",two+""));
    			}else{
    				BigDecimal one = amount.setScale(0,BigDecimal.ROUND_DOWN);
					BigDecimal two =amount.subtract(one).multiply(BigDecimal.valueOf(10)).setScale(1,BigDecimal.ROUND_DOWN);
					two = two.subtract(two.setScale(0,BigDecimal.ROUND_DOWN)).compareTo(BigDecimal.valueOf(0)) > 0 ? two : two.setScale(0, BigDecimal.ROUND_DOWN);
					couponBag.setReduce_cost(Lists.newArrayList(one+"",(two+"").replaceAll("\\.", "")));
    			}
    		}
            if(marketingResponseVo.getMarketingType()==0) {
            	couponBags.add(couponBag);
            }else {
            	cardBags.add(couponBag);
            }
            
        }
        couponBagInfo.setCoupon_bag(couponBags);
        couponBagInfo.setCard_bag(cardBags);
        couponBagInfo.setCode_info(codeInfo);
        return couponBagInfo;
    }

    private String useEndTime(Integer useType, Integer usePeriod, Date useStartTime, Date useEndTime){
        if(useType == 0){
            return afterCouponDate(new Date(), usePeriod);
        }else if(useType == 1){
            return afterCouponDate(useEndTime, 0);
        }
        return "";
    }
    
    private String afterCouponDate(Date startTime, Integer usePeriod){
    	if(startTime == null) {
    		startTime=new Date();
    	}
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(startTime);
        calendar.add(Calendar.DATE, usePeriod);
        Date date = calendar.getTime();
        String outTime = sdf.format(date);
        return outTime;
    }

    //第三方核销数据 处理 TODO 专门用来处理假马甲的函数
//    private AppointmentSubmit checkFlaseStoreIdThirdpartyParsing(String result, AppointmentSubmit appointmentSubmit, String code, String shopId, String thirdShopId, String userId, String type, String shopName){
//        log.info("三方核销**假马甲**数据处理入参：" );
//        log.info("三方接口核销结果--result：" + result);
//        log.info("核销码--code：" + code);
//        log.info("传入店铺Id--shopId：" + shopId);
//        log.info("三方可核销门店ID--thirdShopId：" + thirdShopId);
//        log.info("用户ID--userId：" + userId);
//        log.info("三发类型--type：" + type);
//        log.info("店铺名称--shopName：" + shopName);
//        JSONObject jsonObject = JSONObject.parseObject(result);
//        String resultStatus = jsonObject.get("status").toString();
//        //resultStatus = 1 核销成功  resultStatus = 0 核销失败
//        if("1".equals(resultStatus)){
//            String data = jsonObject.get("data").toString();
//            System.out.println(data);
//            JSONObject jsonCouponId = JSONObject.parseObject(data);
//            String itemId = jsonCouponId.getString("item_id");
//            //1.插入核销表数据 TODO 2019-05-18 还未插入核销表  2019-05-20 对接完成
//            //1-1.组装数据 请求营销系统 TODO 2019-05-18 还未组装数据 2019-05-20 对接完成
//            VerifyReedRedeemCodeParam verifyReedRedeemCodeParam = new VerifyReedRedeemCodeParam();
//            verifyReedRedeemCodeParam.setF_koubei_order_no(jsonCouponId.getString("koubei_order_no"));
//            verifyReedRedeemCodeParam.setF_store_id(shopId);
//            verifyReedRedeemCodeParam.setF_code(code);
//            verifyReedRedeemCodeParam.setF_type(type);
//            verifyReedRedeemCodeParam.setF_channel("2");
//            verifyReedRedeemCodeParam.setF_user_id(userId);
//            verifyReedRedeemCodeParam.setF_koubei_item_id(itemId);
//            verifyReedRedeemCodeParam.setF_remark(shopName);
//            verifyReedRedeemCodeParam.setF_third_store_id(thirdShopId);
//            //团购商品市场价
//            verifyReedRedeemCodeParam.setF_market_price(jsonCouponId.getString("original_price"));
//            //团购商品售价
//            verifyReedRedeemCodeParam.setF_selling_price(jsonCouponId.getString("current_price"));
//            String resultCodeId = marketingFeignService.verifyUserPurchaseRedeemCode(verifyReedRedeemCodeParam);
//            JSONObject jsonObjectCodeId = JSONObject.parseObject(resultCodeId);
//            String statusCodeId = jsonObjectCodeId.get("status").toString();
//            if("0".equals(statusCodeId)){
//                appointmentSubmit.setError(Integer.parseInt(jsonObjectCodeId.get("code").toString()));
//                appointmentSubmit.setReason(jsonObjectCodeId.get("msg"));
//                appointmentSubmit.setContent(new ArrayList<>());
//                return appointmentSubmit;
//            }
//            //2.获取到返回的商品ID 去营销系统兑换优惠劵
//            String dataCodeId = jsonObjectCodeId.get("data").toString();
//            JSONObject jsonObjectDate = JSONObject.parseObject(dataCodeId);
//            log.info("请求营销系统,入参fId--->>>"+jsonObjectDate.get("fId").toString());
//            log.info("请求营销系统,入参fCouponBagId--->>>"+jsonObjectDate.get("fCouponBagId").toString());
//            String resultCheck = marketingFeignService.bindUserPurchaseRedeemCode(jsonObjectDate.get("fId").toString(), jsonObjectDate.get("fCouponBagId").toString());
//            log.info("三方兑换优惠包结果--->>>"+resultCheck);
//            //3.根据兑换信息拼装获取优惠包结果 得到Available_quantity参数组装返回给小程序
//            return checkLocalParsing(resultCheck, appointmentSubmit, code, shopId);
//        }
//        String resultCode = jsonObject.get("code").toString();
//        String resultMsg = jsonObject.get("msg").toString();
//        if("6".equals(type)){
//            appointmentSubmit.setError(Integer.parseInt(resultCode));
//        }else if("15".equals(type)){
//            appointmentSubmit.setError(1);
//        }
//        appointmentSubmit.setReason(resultMsg);
//        appointmentSubmit.setContent(new ArrayList<>());
//        return appointmentSubmit;
//    }
}
